package com.qingge.springboot.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingge.springboot.utils.StringUtil;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingge.springboot.common.Result;

import com.qingge.springboot.service.ITypeService;
import com.qingge.springboot.entity.Type;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 格温不受影响
 * @since 2022-04-01
 */
@RestController
@RequestMapping("/type")
public class TypeController {

    @Resource
    private ITypeService typeService;

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Type type) {
        if (type.getTid() != null) {
            QueryWrapper<Type> wrapper = new QueryWrapper<>();
            wrapper.ne("tid", type.getTid()).
                    eq("tname", type.getTname());
            if (typeService.getOne(wrapper) != null) {
                return Result.error("该类型已存在!");
            }
        }
        typeService.saveOrUpdate(type);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        typeService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        typeService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(typeService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(typeService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam String name,
                           @RequestParam Integer pageNum,
                                @RequestParam Integer pageSize) {
        QueryWrapper<Type> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!StringUtil.isEmptyOrNull(name),"tname",name);
        return Result.success(typeService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

